package com.zhengke.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zhengke.common.util.tools.FdfsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.zhengke.common.util.object.AjaxDone;
import com.zhengke.common.util.tools.CommonUtil;
import com.zhengke.common.util.tools.DateUtil;
import com.zhengke.common.util.tools.LoadProperties;
import com.zhengke.pojo.CommonGoods;
import com.zhengke.pojo.GoodsDetails;
import com.zhengke.pojo.MallServiceGoods;
import com.zhengke.pojo.MallSupplier;
import com.zhengke.pojo.SysDictionaryItem;
import com.zhengke.pojo.TvOrder;
import com.zhengke.pojo.TvOrderGoods;
import com.zhengke.pojo.TvUserOpera;
import com.zhengke.pojo.archie.CurrentUser;
import com.zhengke.pojo.archie.OrderPagination;
import com.zhengke.pojo.archie.TvUser;
import com.zhengke.service.IDiscountService;


/****************************
 * 	创建时间  2020年1月15日 下午3:09:47
 *	项目名称 tvmallws Maven Webapp
 *    @author 刘荣乾
 *    @version 1.0
 *	文件名称：DiscountController.java
 *	类说明：
 ****************************/
@Controller
public class DiscountController extends OrderPagination {
    @Autowired
    private IDiscountService service;

    private AjaxDone json;

    @RequestMapping("toDiscountList")
    public String toDiscountList(HttpServletResponse response, HttpServletRequest request, ModelMap map) {
        CurrentUser user = getCurrentUser(request, response);

        TvUserOpera tvUserOpera = new TvUserOpera();
        tvUserOpera.setId(CommonUtil.createUUID());
        tvUserOpera.setUserId(Integer.parseInt(user.getTvnNo()));
        tvUserOpera.setUserName(user.getUserName());
        tvUserOpera.setType(1);
        tvUserOpera.setTime(DateUtil.currentTime());
        tvUserOpera.setText("打折商品");
        service.insertSelective(tvUserOpera);

        map.put("tmp", new Date());

        return "tv/discount/discountList";
    }

    /**
     * 测试404页面
     *
     * @return
     */
    @RequestMapping("aa")
    public String aaa() {
        return "error/404";
    }


    /**
     * 打折商品列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("discountData")
    public void discountData(HttpServletResponse response, HttpServletRequest request) {
        try {
            CurrentUser cu = getCurrentUser(request, response);
            List<Map<String, Object>> list = service.findDiscount(cu.getStationId());
            List<Map<String, Object>> discountList = new ArrayList<Map<String, Object>>();
            String notPicFount = LoadProperties.findValue("losePicForList");
            for (Map<String, Object> maps : list) {
                Map<String, Object> map = new HashMap<String, Object>();
                String picPath = LoadProperties.findValue("FILE_SERVER_URL") + maps.get("thumb_picPath").toString();
                if (picPath == null || "".equals(picPath)) {
                    picPath = "view.do?path=" + request.getSession().getServletContext().getRealPath(notPicFount);
                } else {
                    //判断如果不为空的话
                    Boolean exist = FdfsUtils.isExist(picPath);
                    if (!exist) {
                        picPath = "view.do?path=" + request.getSession().getServletContext().getRealPath(notPicFount);
                    }
                   /* String begin = picPath.substring(0, 4);
                    if ("http".equals(begin)) {
                        try {
                            URL url = new URL(picPath);
                            URLConnection uc = url.openConnection();
                            //打开的连接读取数据流
                            InputStream in = uc.getInputStream();
                        } catch (Exception e) {
                           // System.err.println("没有");
                            picPath = request.getSession().getServletContext().getRealPath(notPicFount);
                        }
                    } else {
                        File file = new File(picPath);
                        if (!file.exists()) {
                            picPath = request.getSession().getServletContext().getRealPath(picPath);
                        }
                    }*/
                }
                map.put("goodsId", maps.get("goods_id"));
                map.put("picPath", picPath);
                map.put("goodsName", maps.get("goods_name"));
                map.put("goodsPromotionPrice", "￥" + maps.get("goods_price"));
                map.put("type", maps.get("is_normal"));
                discountList.add(map);
            }
            response.setCharacterEncoding("utf-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.getWriter().print("var dataList=" + JSONArray.toJSON(discountList));
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 到商品详情页面
     *
     * @return
     */
    @RequestMapping("toDiscountGoodsDetail")
    public String togoodsDetail(String goodsId, String orderNumber, String type, String pageTitle, ModelMap model, HttpServletRequest request, HttpServletResponse response) {
        //商品类型，“5”打包品，“1”打折品,"0"正品,"2"体验品,"3"积分兑换商品,"7"可兑换打包品，
        CurrentUser user = getCurrentUser(request, response);
        /*System.err.println(type + "=================================");
        System.err.println(goodsId + "=======================================");*/

        model.put("pageTitle", pageTitle);
        model.put("tmp", new Date());

        String i = service.queryParamValueByItemId("00010001");
        String[] str = i.split(":");
        double a = Double.parseDouble(str[0]);
        double b = Double.parseDouble(str[1]);
        try {
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            double commonPrice = 0.0d;
            if ("1".equals(type) || "2".equals(type) || "3".equals(type) || "7".equals(type)) {
                list = service.findGoodsDetail(goodsId);
            } else {
                list = service.findGoodsDetail2(goodsId);
                if ("5".equals(type)) {
                    if (list.size() > 0) {
                        List<Map<String, Object>> list3 = service.findBaleGoods(list.get(0).get("").toString());
                        for (Map<String, Object> map : list3) {
                            commonPrice += (Double.parseDouble(map.get("goods_price").toString()) * Integer.parseInt(map.get("goods_num").toString()));
                        }
                    }
                }
            }
            String fileServerUrl = LoadProperties.findValue("FILE_SERVER_URL");
            for (Map<String, Object> obj : list) {
                String infoPicPath = fileServerUrl + obj.get("info_picPath").toString();
                String notInfoPic = LoadProperties.findValue("loseInfoPicForGoodsDetail");
                if (infoPicPath == null || "".equals(infoPicPath))
                    infoPicPath = "view.do?path=" + request.getSession().getServletContext().getRealPath(notInfoPic);
                else {
                    Boolean exist = FdfsUtils.isExist(infoPicPath);
                    if (!exist) {
                        infoPicPath = "view.do?path=" + request.getSession().getServletContext().getRealPath(notInfoPic);
                    }
                }

                List<String> rtnList = new ArrayList<String>();

                if (obj.get("picPath1") != null && !"".equals(obj.get("picPath1")))
                    rtnList.add(fileServerUrl + obj.get("picPath1").toString());
                if (obj.get("picPath2") != null && !"".equals(obj.get("picPath2")))
                    rtnList.add(fileServerUrl + obj.get("picPath2").toString());
                if (obj.get("picPath3") != null && !"".equals(obj.get("picPath3")))
                    rtnList.add(fileServerUrl + obj.get("picPath3").toString());
                if (obj.get("picPath4") != null && !"".equals(obj.get("picPath4")))
                    rtnList.add(fileServerUrl + obj.get("picPath4").toString());
                if (obj.get("picPath5") != null && !"".equals(obj.get("picPath5")))
                    rtnList.add(fileServerUrl + obj.get("picPath5").toString());

                if (rtnList.size() == 0) {
                    String notFoundPic = LoadProperties.findValue("losePicForGoods");
                    rtnList.add("view.do?path=" + request.getSession().getServletContext().getRealPath(notFoundPic));
                }
                if ("1".equals(type)) {
                    model.put("commonPrice", "￥" + obj.get("common_price"));//原价
                }
                if ("5".equals(type)) {
                    model.put("commonPrice", "￥" + commonPrice);//原价
                }

                if ("3".equals(type) || "7".equals(type)) {
                    String goodsPrice = obj.get("goods_price") == null ? "" : obj.get("goods_price").toString();
                    double d = Double.parseDouble(goodsPrice) * (a / b);
                    model.put("commonPrice", d);//所需兑换积分
                }

                String shippingFee = obj.get("shipping_fee") == null ? "" : obj.get("shipping_fee").toString();
                double s = Double.parseDouble(shippingFee) * (a / b);
                model.put("shippingFee", s);//运费

                TvUserOpera tvUserOpera = new TvUserOpera();
                tvUserOpera.setId(CommonUtil.createUUID());
                tvUserOpera.setUserId(Integer.parseInt(user.getTvnNo()));
                tvUserOpera.setUserName(user.getUserName());
                tvUserOpera.setType(4);
                tvUserOpera.setTime(DateUtil.currentTime());
                tvUserOpera.setText(obj.get("goods_name").toString());
                service.insertSelective(tvUserOpera);

                model.put("goodsId", goodsId);
                model.put("picList", rtnList);
                model.put("picList", rtnList);
                model.put("goodsName", obj.get("goods_name"));
                model.put("goodsPrice", "￥" + obj.get("goods_price"));//打折价
                model.put("deliveryWay", "门店自提");//收货方式
                model.put("supplierName", obj.get("supplier_name"));//供应商名称
                model.put("supplierId", obj.get("supplier_id"));//供应商id
                model.put("infoPicPath", infoPicPath);//介绍图片
                model.put("awardedIntegral", obj.get("awarded_integral"));//赠送积分
                model.put("specifications", obj.get("specifications"));//商品规格
            }
            if (orderNumber == null || "".equals(orderNumber))
                model.put("orderNumber", 1);
            else
                model.put("orderNumber", orderNumber);

            //图片查询滚动时间
            model.put("time", "1000");//轮播图片滚动时间
            if ("0".equals(type) || "2".equals(type)) {
                model.put("show", "0");//显示类型
            } else {
                model.put("show", "1");//显示类型
            }
            model.put("type", type);//商品类型


        } catch (Exception e) {
            e.printStackTrace();
        }
        return "tv/discount/GoodsDetails";
    }

    /**
     * 到订单页面
     *
     * @return
     */
    @RequestMapping("toOrderPage")
    public String toOrderPage(String goodsId, String number, String type, String shippingFee, String goodsPrice, String specifications, ModelMap model, HttpServletResponse response, HttpServletRequest request) {

        try {
            CurrentUser cu = getCurrentUser(request, response);
            model.put("userName", cu.getUserName());//用户名(收货人姓名)
            model.put("phone", cu.getPhone());//电话（收货人电话
            model.put("address", cu.getAddressDetail());//收货地址

            //收货方式
            String receiptTime = cu.getReceiptTime();
			/*if(receiptTime==null){
				ActionContext.getContext().put("flag", "rt");//区分不同功能
				return "setReceiptTime";
			}
			else*/
            model.put("receiptTime", receiptTime);
            //System.err.println(type + "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
            //System.err.println(goodsId + "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
            String deliveryWay = cu.getDeliveryWay();
            if ("".equals(deliveryWay)) {
                model.put("flag", "dw");//区分不同功能
                model.put("goodsId", goodsId);
                model.put("number", number);
                model.put("tmp", CommonUtil.createUUID());
                return "setDeliverWay";
            } else {
                model.put("deliverWay", deliveryWay);
            }

            CommonGoods commonGoods = null;
            GoodsDetails goodsDetail = null;
            if ("0".equals(type) || "5".equals(type)) {
                commonGoods = service.findCommonGoodsById(goodsId);
            } else {
                goodsDetail = service.findGoodsDetailsById(goodsId);
                commonGoods = service.findCommonGoodsById(goodsDetail.getCommonGoodsId().toString());
            }
            model.put("goodsName", commonGoods.getGoodsName());

            int sendIntegral = 0;
            //订单商品总价
            BigDecimal num = new BigDecimal(number);
            BigDecimal total = new BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal total2 = new BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP);
            if ("0".equals(type) || "5".equals(type)) {
                BigDecimal price = new BigDecimal(commonGoods.getCommonPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
                total = price.multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
                model.put("price", price);
                model.put("total", total);
                sendIntegral = commonGoods.getSendInte() * Integer.parseInt(number);
            } else if ("3".equals(type) || "7".equals(type)) {
                BigDecimal gPriceInte2 = new BigDecimal(goodsPrice).setScale(2, BigDecimal.ROUND_HALF_UP);
                total2 = gPriceInte2.multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);

                model.put("price", gPriceInte2);
                model.put("total", total2);
                sendIntegral = goodsDetail.getAwardedIntegral() * Integer.parseInt(number);
            } else {
                BigDecimal price = new BigDecimal(goodsDetail.getGoodsPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
                total = price.multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
                model.put("price", price);
                model.put("total", total);
                sendIntegral = goodsDetail.getAwardedIntegral() * Integer.parseInt(number);
            }
            //订单总价
            BigDecimal shippingFees = new BigDecimal(commonGoods.getShippingFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
            if ("0".equals(deliveryWay)) {
                BigDecimal sFeeInte2 = new BigDecimal(shippingFee).setScale(2, BigDecimal.ROUND_HALF_UP);
                BigDecimal sFeeInte2Total = sFeeInte2.multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
                if ("3".equals(type) || "7".equals(type)) {
                    BigDecimal orderAmount = total2.add(sFeeInte2).setScale(2, BigDecimal.ROUND_HALF_UP);
                    model.put("total2", orderAmount.doubleValue());//订单总价
                } else {
                    BigDecimal orderAmount = total.add(shippingFees).setScale(2, BigDecimal.ROUND_HALF_UP);
                    model.put("total2", orderAmount.doubleValue());//订单总价
                }
                model.put("shippingFee", sFeeInte2Total.doubleValue());//配送积分
            } else {
                if ("3".equals(type) || "7".equals(type)) {
                    model.put("total2", total2.doubleValue());//订单总价
                } else
                    model.put("total2", total.doubleValue());//订单总价
            }

            model.put("sendIntegral", sendIntegral);//赠送积分
            model.put("number", number);

            model.put("goodsId", goodsId);
            model.put("type", type);
            model.put("flag", "normal");//区分不同功能
            model.put("tmp", CommonUtil.createUUID());
            model.put("specifications", specifications);//商品规格
        } catch (Exception e) {
            e.printStackTrace();
            return "error/404";
        }
        return "tv/discount/orderPage";
    }

    /**
     * 设置收货方式
     *
     * @return
     */
    @RequestMapping("doSetDeliveryWay")
    public @ResponseBody
    AjaxDone doSetDeliveryWay(ModelMap model, HttpServletResponse response, HttpServletRequest request, String way, String goodsId, String number) {

        CurrentUser cu = getCurrentUser(request, response);
        try {
            TvUser tu = service.findTvUser(cu.getTvnNo());
            tu.setDelivery_way(way);
            service.updateUser(tu);
            Map<String, String> rtnMap = new HashMap<String, String>();
            rtnMap.put("goodsId", goodsId);
            rtnMap.put("number", number);
            json = new AjaxDone("200", "设置成功！", rtnMap);
            cu.setDeliveryWay(way);

            model.put(SESSION_USER_KEY, cu);

        } catch (Exception e) {
            json = new AjaxDone("300", "设置失败！", null);
        }

        return json;
    }

    /**
     * 到设置收货时间页面
     *
     * @return
     */
    @RequestMapping("toSetTime")
    public String setTime(ModelMap model, HttpServletResponse response, HttpServletRequest request, String way, String goodsId, String number) {

        model.put("goodsId", goodsId);
        model.put("number", number);
        model.put("way", way);
        model.put("tmp", CommonUtil.createUUID());

        return "tv/discount/setReceiptTime";
    }

    /**
     * 查询系统设置的收货时间
     */
    @ResponseBody
    @RequestMapping("queryReceiptTime")
    public void queryReceiptTime(HttpServletResponse response) {

        List<SysDictionaryItem> list = service.finDictionaryItems("0003");
        try {
            response.setCharacterEncoding("utf8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.getWriter().print("var dataList=" + JSONArray.toJSON(list));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置收货时间
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("setReceiptTime")
    public AjaxDone setReceiptTime(ModelMap model, HttpServletResponse response, HttpServletRequest request, String way, String goodsId, String number, String time) {
        try {
            CurrentUser cu = getCurrentUser(request, response);
            TvUser tu = service.findTvUser(cu.getTvnNo());
            tu.setDelivery_way(way);
            tu.setReceipt_time(time);
            service.updateUser(tu);
            Map<String, String> rtnMap = new HashMap<String, String>();
            rtnMap.put("goodsId", goodsId);
            rtnMap.put("number", number);
            tu.setDelivery_way(way);
            tu.setReceipt_time(time);
            model.put(SESSION_USER_KEY, cu);
            json = new AjaxDone("200", "设置成功！", rtnMap);
        } catch (Exception e) {
            e.printStackTrace();
            json = new AjaxDone("300", "设置失败！", null);
        }
        return json;
    }

    /**
     * 生成订单
     *
     * @param goodsId
     * @param number
     * @param type
     * @param shippingFee    运费所需积分
     * @param goodsPrice     商品所需积分
     * @param specifications 商品规格
     * @return
     */
    @ResponseBody
    @RequestMapping("createOrder")
    public AjaxDone createOrder(ModelMap model, HttpServletResponse response, HttpServletRequest request, String goodsId, String number, String type, String shippingFee, String goodsPrice, String specifications) {
        //商品类型，“5”打包品，“1”打折品,"0"正品,"2"体验品,"3"积分兑换商品,"7"可兑换打包品，
        try {
            CurrentUser cu = getCurrentUser(request, response);

            String goodType = "0";
            if ("0".equals(type) || "5".equals(type))
                goodType = type;
            else
                goodType = "6";

            List<MallServiceGoods> list = service.findServiceGoods(cu.getStationId(), goodsId, goodType);
            MallServiceGoods msg = null;
            if (list.size() > 0) {
                msg = list.get(0);
                if (msg.getGoodsDestineQuota() < Integer.parseInt(number)) {
                    json = new AjaxDone("300", "下单失败，商品剩余数量不足！", null);
                    return json;
                }
			/*
			if(list2.size()>0){
				int a = Integer.parseInt(list2.get(0)[0].toString());
				if(a>=msg.getGoodsDestineQuota()){
					json = new AjaxDone("300","下单失败，商品剩余数量不足！",null);
					return "ajaxResult";
				}
			}*/
                //id = msg.getId();
            } else {
                json = new AjaxDone("300", "下单失败，该商品已下架！", null);
                return json;
            }

            CommonGoods commonGoods = null;
            GoodsDetails goodsDetail = null;
            if ("0".equals(type) || "5".equals(type)) {
                commonGoods = (CommonGoods) service.findCommonGoodsById(goodsId);
            } else {
                goodsDetail = (GoodsDetails) service.findGoodsDetailsById(goodsId);
                commonGoods = (CommonGoods) service.findCommonGoodsById(goodsDetail.getCommonGoodsId().toString());
            }
            /*
             *构造保存订单商品信息
             */
            TvOrderGoods tog = new TvOrderGoods();
            tog.setGoodsId(Integer.parseInt(goodsId));
            tog.setGoodsName(commonGoods.getGoodsName());


            /*
             *构造保存订单信息
             */
            TvOrder to = new TvOrder();
            to.setOrderSn(service.createOrderSn(cu.getTvnNo()));//订单编号
            to.setUserId(cu.getTvnNo()); //用户id tvn号码
            to.setUserName(cu.getUserName());//用户名称
            to.setUserCardNumber(cu.getUserCardNo()); //用户卡号
            to.setAddTime(DateUtil.getSystemDateTime());//生成时间
            tog.setGoodsTime(DateUtil.getSystemDate());

            //订单商品总价
            BigDecimal num = new BigDecimal(number);
            BigDecimal total = new BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal price = new BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP);
            if ("0".equals(type) || "5".equals(type)) {
                price = new BigDecimal(commonGoods.getCommonPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
                total = price.multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
            } else if ("3".equals(type) || "7".equals(type)) {
                price = new BigDecimal(goodsPrice).setScale(2, BigDecimal.ROUND_HALF_UP);
                total = price.multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
            } else {
                price = new BigDecimal(goodsDetail.getGoodsPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
                total = price.multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
            }

            tog.setGoodsPrice(price.doubleValue());//商品价格
            tog.setGoodsPayPrice(price.doubleValue());//商品实际成交价
            to.setGoodsAmount(total.doubleValue());    //订单商品总价


            //查询用户积分
            //TvUser tvUser = (TvUser) commonService.getByID(TvUser.class, cu.getTvnNo());
            //List<Object[]> listI = service.findInteGoods(cu.getTvnNo());

            //订单总价
            String deliveryWay = cu.getDeliveryWay();
            BigDecimal shippingFee1 = new BigDecimal(commonGoods.getShippingFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal shippingFee2 = new BigDecimal(shippingFee).setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal shippingFee3 = new BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal orderAmount = new BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP);

            if (deliveryWay == "0") {
                if ("3".equals(type) || "7".equals(type)) {
                    shippingFee3 = shippingFee2.multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
                    orderAmount = total.add(shippingFee3).setScale(2, BigDecimal.ROUND_HALF_UP);
			/*if(listI.size()>0){
				double d = Double.parseDouble(listI.get(0)[0].toString());
				if(orderAmount.doubleValue()+d>tvUser.getUserIntegral()){
					json = new AjaxDone("300","下单失败，您的积分不够！",null);
					return "ajaxResult";
				}
			}*/
                } else {
                    shippingFee3 = shippingFee1.multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
                    orderAmount = total.add(shippingFee3).setScale(2, BigDecimal.ROUND_HALF_UP);
                }
                BigDecimal shippingFee4 = shippingFee2.multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
                to.setShippingFee(shippingFee4.doubleValue());//订单运费

                to.setOrderAmount(orderAmount.doubleValue());//订单总价
                to.setDeliveryTime(cu.getReceiptTime());//送货时间段
            } else {
			/*if("3".equals(type)||"7".equals(type)){
			if(listI.size()>0){
				double d = Double.parseDouble(listI.get(0)[0].toString());
				if(total.doubleValue()+d>tvUser.getUserIntegral()){
					json = new AjaxDone("300","下单失败，您的积分不够！",null);
					return "ajaxResult";
				}
			}
		}*/
                to.setOrderAmount(total.doubleValue());//订单总价
            }
            to.setOrderState((short) 10);//订单状态  生成时设定已确认  订单状态：0:已取消;10(默认):待确认;20:已确认;30:已配货;40:已发货;50:已收款;60:已退货

            //技术订单商品赠送积分
            BigDecimal integral = new BigDecimal(commonGoods.getSendInte()).multiply(num).setScale(2, BigDecimal.ROUND_HALF_UP);
            if ("1".equals(type) || "5".equals(type))
                to.setIntegralHandsel(0.0d);//订单赠送积分
            else
                to.setIntegralHandsel(integral.doubleValue());//订单赠送积分

            to.setServicePointId(Integer.parseInt(cu.getStationId()));//服务点id

            to.setReceiverName(cu.getUserName()); //收货人姓名
            to.setReceiverAddress(cu.getAddressDetail()); //收货人地址
            to.setReceiveProvinceId(Integer.parseInt(cu.getProvinceId()));//收货人省份id
            to.setReceiveCityId(Integer.parseInt(cu.getCityId()));//收货人城市id
            to.setReceiptMethod(cu.getDeliveryWay());
            to.setReceiverPhone(cu.getPhone());

            //继续保存订单商品信息
            if ("2".equals(type)) {
                to.setIsExperie((short) 1);
            } else if ("3".equals(type) || "7".equals(type)) {
                to.setIsExperie((short) 2);
            } else {
                to.setIsExperie((short) 0);
            }
            tog.setIsDelivery((short) 0);

            tog.setGoodsNum(Short.parseShort(number));
            tog.setServicePointId(Integer.parseInt(cu.getStationId()));
            tog.setUserId(cu.getTvnNo());
            tog.setGoodsType(Short.parseShort(type));//商品属性(1默认2折扣商品3打包组合4体验品)
            tog.setState((short) 1);
            tog.setSpecifications(specifications);//商品规格

            //减少预定限额
            msg.setGoodsDestineQuota(msg.getGoodsDestineQuota() - Integer.parseInt(number));
            service.createOrder(to, tog, msg);
            json = new AjaxDone("200", "您的订单已生成！", null);

        } catch (Exception e) {
            e.printStackTrace();
            json = new AjaxDone("300", "下单失败，请稍后再试！", null);
        }
        return json;
    }


    /**
     * 到提示页面
     *
     * @return
     */
    @RequestMapping("toTips")
    public String toTips() {

        return "tv/discount/tips";
    }


    /**
     * 供应商信息
     *
     * @return
     */
    @RequestMapping("toSupplierDetail")
    public String toSupplierDetail(String supplierId, ModelMap model) {
        try {
            MallSupplier ms = service.findMallSupplier(Integer.parseInt(supplierId));
            model.put("ms", ms);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "tv/discount/toSupplierDetail";
    }


    @ResponseBody
    @RequestMapping("getJson")
    public AjaxDone getJson() {
        return json;
    }

    @ResponseBody
    @RequestMapping("setJson")
    public void setJson(AjaxDone json) {
        this.json = json;
    }


}
